package com.niujie.prototypemanage.rest;

import com.github.pagehelper.PageHelper;
import com.niujie.prototypemanage.dto.ResultDTO;
import com.niujie.prototypemanage.exception.CustomizeErrorCode;
import com.niujie.prototypemanage.mapper.PrototypeMapper;
import com.niujie.prototypemanage.model.Prototype;
import com.niujie.prototypemanage.model.PrototypeExample;
import com.niujie.prototypemanage.utils.ZipUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

//@Controller
@RequestMapping("prototype")
@RestController
public class PrototypeController {

    @Value("${prototype.file.path}")
    public String filepath;

    @Value("${prototype.deploy.path}")
    public String deploypath;
    @Resource
    public PrototypeMapper prototypeMapper;

    @GetMapping
    public ResultDTO listProto(@RequestBody(required=true) Map<String,Object> map){
        Integer pageSize = Integer.valueOf(map.get("pageSize").toString());
        Integer pageNum = Integer.valueOf(map.get("pageNum").toString());
        String keywords = map.get("keywords").toString();
        PrototypeExample prototypeExample = new PrototypeExample();
        prototypeExample.createCriteria()
                .andNameLike("%"+keywords+"%")
                .andIsDeleteEqualTo(false);
        PageHelper.startPage(pageNum,pageSize);
        List<Prototype> prototypeList = prototypeMapper.selectByExample(prototypeExample);
        return ResultDTO.okOf(prototypeList);
    }


    @PostMapping
    public ResultDTO addProto(Prototype prototype,
                              @RequestParam(value = "file",required = false) MultipartFile file) throws IOException {
        System.out.println(file.getContentType());
        if(file.isEmpty()||!file.getContentType().equals("application/zip")) return ResultDTO.errorOf(CustomizeErrorCode.FILE_NOT_FOUND);
        PrototypeExample prototypeExample = new PrototypeExample();
        prototypeExample.createCriteria()
                .andProjectIdEqualTo(prototype.getProjectId())
                .andNameEqualTo(prototype.getName());
        List<Prototype> prototypes = prototypeMapper.selectByExample(prototypeExample);
//创建prototype的模板类
        Prototype prototypeNew = new Prototype();
        BeanUtils.copyProperties(prototype,prototypeNew);
        prototypeNew.setPrototypeId(null);
        String a="1.2.3.54".split("\\.")[0];
        String randomName = (UUID.randomUUID().toString().replace("-","")+file.getOriginalFilename()).split("\\.")[0];
        String filename = System.getProperty("user.dir")+filepath+randomName;
        prototypeNew.setFilepath(filename);
        prototypeNew.setIsDelete(false);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date(System.currentTimeMillis()));
        prototypeNew.setCreateTime(format);
        prototypeNew.setUpdateTime(format);

        File fileUnzip = new File(filename);
        if(prototypes.isEmpty()) {
            if(!fileUnzip.exists()) fileUnzip.mkdirs();
            File fileSave = new File(filename+".zip");
            file.transferTo(fileSave);
            ZipUtil.unZip(fileSave,filename);
            ZipUtil.unZip(fileSave,System.getProperty("user.dir")+deploypath);
            prototypeMapper.insert(prototypeNew);
            return ResultDTO.okOf();
        } else if(prototypes.get(0).getIsDelete()){
            if(!fileUnzip.exists()) fileUnzip.mkdirs();
            File fileSave = new File(filename+".zip");
            file.transferTo(fileSave);
            ZipUtil.unZip(fileSave,filename);
            ZipUtil.unZip(fileSave,System.getProperty("user.dir")+deploypath);
            prototypeNew.setPrototypeId(prototypes.get(0).getPrototypeId());
            PrototypeExample updatePrototypeExample = new PrototypeExample();
            updatePrototypeExample.createCriteria()
                    .andPrototypeIdEqualTo(prototypes.get(0).getPrototypeId());
            prototypeMapper.updateByExample(prototypeNew,updatePrototypeExample);
            return ResultDTO.okOf();
        }
        else{
            return ResultDTO.errorOf(CustomizeErrorCode.USER_ALREADY_EXIST);
        }
    }

    @DeleteMapping
    public ResultDTO deleteProto(@RequestBody(required=true) Map<String,Object> map){
        Integer protoId = Integer.valueOf(map.get("protoId").toString());
        Prototype prototype = prototypeMapper.selectByPrimaryKey(protoId);
        if(prototype==null){
            return ResultDTO.errorOf(CustomizeErrorCode.USER_NOT_FOUND);
        }else {
            PrototypeExample prototypeExample = new PrototypeExample();
            prototypeExample.createCriteria()
                    .andPrototypeIdEqualTo(protoId);
            Prototype prototypeDelete = new Prototype();
            prototypeDelete.setIsDelete(true);
            prototypeMapper.updateByExampleSelective(prototype,prototypeExample);
        }
        return ResultDTO.okOf();
    }

    @PutMapping
    public ResultDTO putProto(@RequestBody Prototype prototype){
        PrototypeExample prototypeExample = new PrototypeExample();
        prototypeExample.createCriteria()
                .andProjectIdEqualTo(prototype.getProjectId())
                .andNameEqualTo(prototype.getName());
        List<Prototype> prototypes = prototypeMapper.selectByExample(prototypeExample);
        if(!prototypes.isEmpty()&&!prototypes.get(0).getIsDelete()) {
            PrototypeExample putPrototypeExample = new PrototypeExample();
            prototypeExample.createCriteria()
                    .andPrototypeIdEqualTo(prototype.getPrototypeId());
            prototypeMapper.updateByExampleSelective(prototype, putPrototypeExample);
            return ResultDTO.okOf();
        } else {
            return ResultDTO.errorOf(CustomizeErrorCode.USER_NOT_FOUND);
        }
    }

    @GetMapping("/deploy")
    public ResultDTO deploy(Integer prototypeId){
        Prototype prototype = prototypeMapper.selectByPrimaryKey(prototypeId);
        String filepath = prototype.getFilepath();
        File file = new File(filepath);
        File[] files = file.listFiles();
        List<String> htmls = new ArrayList<>();
        for (File file1 : files) {
            htmls.add(file1.getName());
        }
        return ResultDTO.okOf(htmls);
    }

    @GetMapping("deploy/{htmlName}")
    public ModelAndView getHtml(@PathVariable("htmlName") String htmlName){
        ModelAndView modelAndView = new ModelAndView(htmlName);
        return modelAndView;
    }

//    @GetMapping("upload")
//    public String upload(MultipartFile file) throws IOException {
//        String randomName=UUID.randomUUID().toString().replace("-","")+file.getOriginalFilename();
//        String filename=filepath + randomName;
//        File fileNew = new File(filename);
//        if(!fileNew.getParentFile().exists()) fileNew.getParentFile().mkdir();
//        file.transferTo(fileNew);
//        return filename;
//    }
}
